package com.api.gbhg.luoao.web;

import com.alibaba.fastjson.JSON;
import com.api.gbhg.luoao.utils.ApperverDao;
import com.api.gbhg.zengping.dao.PropertyManagementCostDao;
import com.api.gbhg.zengping.page.PageInfo;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.*;

/**
 * 授权列表功能
 *
 */
@Path("/Approve")
public class ApproveApi {

    public static final Logger LOGGER= LoggerFactory.getLogger("gbhg");
    /**
     * 授权列表显示
     * @param maps
     * @return
     */
    @POST
    @Path("/approverlist")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getapproverlist(Map<String,Object> maps){
        PropertyManagementCostDao rmcd=new PropertyManagementCostDao();
        int pageNum = Integer.parseInt(maps.get("pageNum").toString());
        int pageSize = Integer.parseInt(maps.get("pageSize").toString());
        pageNum = (pageNum - 1) * pageSize;

        RecordSet rs = new RecordSet();
        /*rs.executeQuery("select  ny.subcompanyname,wh.ysbzhpr,wh.ysbzjbr,wh.id from uf_dwysbzrywh wh, hrmsubcompany ny\n" +
                "where  wh.bmxfdcs = ny.id\n" +
                "order by  wh.id  offset "+pageNum+" rows fetch next "+pageSize+" rows only\n");*/
        String sql="select * from HrmSubcompanyDefined where convert(varchar,ysbzhpr)<>'' "+
                "order by  id  offset "+pageNum+" rows fetch next "+pageSize+" rows only";
        LOGGER.info("查询授权列表==>"+sql);
        rs.executeQuery(sql);

        Map<String, Object>[] map = new HashMap[rs.getArray().size()];
        int i = 0;
        while (rs.next()){
            map[i] = new HashMap<>();
            //id
            map[i].put("id",rs.getStringNoTrim("id"));
            //单位
            map[i].put("subcompanyname",conversion(rs.getInt("subcomid")));
            map[i].put("subcompanyid",rs.getInt("subcomid"));
            //经办人
            String ysbzjbr = rs.getString("ysbzjbr");
            map[i].put("ysbzjbrid",ysbzjbr);
            map[i].put("ysbzjbr",Strings.isNullOrEmpty(ysbzjbr)?"":rmcd.getUserNameByIds(rs.getString("ysbzjbr")));
            //核批人
            String ysbzhpr = rs.getString("ysbzhpr");
            map[i].put("ysbzhprid",ysbzhpr);
            map[i].put("ysbzhpr",Strings.isNullOrEmpty(ysbzhpr)?"":rmcd.getUserNameByIds(rs.getString("ysbzhpr")));
            //财务人员
            String dwyscwry = rs.getString("dwyscwry");
            map[i].put("dwyscwryid",dwyscwry);
            map[i].put("dwyscwry", Strings.isNullOrEmpty(dwyscwry)?"":rmcd.getUserNameByIds(rs.getString("dwyscwry")));
            i++;
        }

        PageInfo page = new PageInfo();
        page.setList(map);
        page.setPageNum(Integer.parseInt(maps.get("pageNum").toString()));
        page.setPageSize(pageSize);
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery("select count(1)total from HrmSubcompanyDefined where convert(varchar,ysbzhpr)<>'' ");
        recordSet.next();
        page.setTotal(recordSet.getInt("total"));
        return JSON.toJSONString(page);
    }

    //部门id得到部门名称
    public String conversion(int deptid){
        String sql="select subcompanyname from hrmsubcompany where id="+deptid;
        LOGGER.info("部门id得到部门名称====>"+sql);
        RecordSet rs=new RecordSet();
        rs.executeQuery(sql);
        String str=null;
        while (rs.next()){
            str=rs.getString("subcompanyname");
        }
        return str;
    }

    //授权列表数据插入
    @POST
    @Path("/approverInsert")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String approverInsert(Map<String,Object> maps){
        Map<String,Object> map = new HashMap<>();
        if (!flagImpower(maps,null)) {
            return JSON.toJSONString(map.put("result","false"));
        }
        String ysbzhpr = new BaseBean().getPropValue("gbhg-zpshouquan", "ysbzhpr");
        String ysbzjbr = new BaseBean().getPropValue("gbhg-zpshouquan", "ysbzjbr");
        String cwry = new BaseBean().getPropValue("gbhg-zpshouquan", "cwry");
        //数据插入至授权列表 建模授权列表
        boolean insertApperver = ApperverDao.insertApperver(maps);
        //数据更新至矩阵表
        boolean updateMatrix = ApperverDao.UpdateMatrix(maps);
        //数据插入至角色表
        boolean insertRole = ApperverDao.insertRole(maps);

        if (insertApperver && updateMatrix && insertRole){
            map.put("result","true");
        }else {
            map.put("result","false");
        }
        return JSON.toJSONString(map);
    }

    //新增和删除验证
    public boolean flagImpower(Map<String,Object> map,Integer delete){
        String sql="SELECT * FROM HrmSubcompanyDefined t where subcomid="+map.get("dw");
        RecordSet rs=new RecordSet();
        rs.executeQuery(sql);
        while (rs.next()){
            //因为sqlserver没有对应的函数,所以需要借助集合的方式去重后达到修改的目的
            //得到查询的字段列表 (字段列表用逗号拆分转为数组-->转为set集合) set集合进行参数去重,删除参数达到修改的目的.
            //更新SQL语句
            HashSet<String> set1=new HashSet<>(Arrays.asList(rs.getString("ysbzjbr").split(",")));
            HashSet<String> set2=new HashSet<>(Arrays.asList(rs.getString("ysbzhpr").split(",")));
            HashSet<String> set3=new HashSet<>(Arrays.asList(rs.getString("dwyscwry").split(",")));
            Set<String> ysbzjbr =new HashSet<>( Arrays.asList(map.get("ysbzjbr").toString().split(",")));
            Set<String> ysbzhpr = new HashSet<>(Arrays.asList(map.get("ysbzhpr").toString().split(",")));
            Set<String> dwyscwry = new HashSet<>(Arrays.asList(map.get("dwyscwry").toString().split(",")));
            if (set1.contains(ysbzjbr)&&set2.contains(ysbzhpr)&&set3.contains(dwyscwry)) {
                if(delete!=null){
                    set1.removeAll(ysbzjbr);
                    set2.removeAll(ysbzhpr);
                    set3.removeAll(dwyscwry);
                    //修改矩阵
                    RecordSetTrans rst=new RecordSetTrans();
                    String updatesql="update HrmSubcompanyDefined set ysbzjbr=?,ysbzhpr=?,dwyscwry=? where subcomid="+map.get("dw");
                    try {
                        rst.executeUpdate(updatesql,String.join(",",set1),String.join(",",set2),String.join(",",set3));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //删除矩阵元素
                    return true;
                }
                //已存在,不能添加
                return false;
            }
            return true;
        }
        return true;
    }

    public static void main(String[] args) {
        Map<String,Object> map=new HashMap<>();
        map.put("aaa","1,2,3");
        HashSet<String> stt1=new HashSet<>();
        stt1.add("1");
        stt1.add("2");
        stt1.add("3");
        if (stt1.contains(map.get("aaa").toString())) {
            stt1.remove(map.get("aaa").toString());
            System.out.println(stt1.toString());
            System.out.println(String.join(",",stt1));
        }
       Set<String> set=new HashSet<>(Arrays.asList("1","2","3","4"));
        String[] aaas = map.get("aaa").toString().split(",");
        Set<String> set1=new HashSet<>(Arrays.asList(aaas));
        set.removeAll(set1);
        System.out.println(set);

    }




    //授权列表数据更新
//    @POST
//    @Path("/approverUpdeta")
//    @Produces(MediaType.APPLICATION_JSON)
//    public String approverUpdate(Map<String,Object> maps){
//        RecordSetTrans rst=new RecordSetTrans();
//        rst.setAutoCommit(false);//自动提交为false
//        Map<String,Object> map = new HashMap<>();
//
//        //更新角色表
//        boolean UpdateRole = ApperverDao.UpdateRole(rst,maps);
//        //更新授权列表数据
//        boolean UpdetaApperverId = ApperverDao.UpdetaApperverId(maps);
//        //数据更新至矩阵表
//        boolean updateMatrix = ApperverDao.UpdateMatrix(maps);
//
//        if (UpdateRole && updateMatrix && UpdetaApperverId){
//            map.put("result","true");
//        }else {
//            map.put("result","false");
//        }
//
//        return JSON.toJSONString(map);
//    }



    //授权列表数据删除


    @POST
    @Path("/approverDelete")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String approverDelete(Map<String,Object> maps){
        //删除角色表中的数据
        String ysbzhprRole = new BaseBean().getPropValue("gbhg-zpshouquan", "ysbzhpr");
        String ysbzjbrRole = new BaseBean().getPropValue("gbhg-zpshouquan", "ysbzjbr");
        String cwryRole = new BaseBean().getPropValue("gbhg-zpshouquan", "cwry");
        boolean b1 = ApperverDao.DeleteRole(ysbzhprRole,maps.get("ysbzhpr").toString(),"ysbzhpr");//预算管理-收入预算角色
        boolean b2 = ApperverDao.DeleteRole(ysbzjbrRole,maps.get("ysbzjbr").toString(),"ysbzjbr");//预算管理-支出预算角色
        boolean b3 = ApperverDao.UpdateMatrix(maps.get("dw").toString());
        //根据id删除授权表中的数据
        boolean DeleteApperverId = ApperverDao.DeleteApperverId(maps);

        boolean updateMatrix = false ;
        RecordSetTrans rs=new RecordSetTrans();
        try {
            if(b1 && b2 && b3){
                //String sql="delete from HrmSubcompanyDefined where subcomid="+maps.get("dw");
                String sql="update HrmSubcompanyDefined set ysbzjbr='',ysbzhpr='',dwyscwry=''  where subcomid="+maps.get("dw");
                LOGGER.info("更新分部自定义字段表财务角色有关内容-->"+sql);
                updateMatrix = rs.executeUpdate(sql);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<>();
        if (updateMatrix && b1 && b2 && b3){
            map.put("result","true");
        }else {
            map.put("result","false");
        }
        return JSON.toJSONString(map);
    }

}
